package com.sunshine.lnuplus.ui.activity

import android.app.Activity
import android.content.DialogInterface
import android.graphics.Color
import android.os.Bundle
import android.view.*
import android.widget.Button
import android.widget.DatePicker
import android.widget.EditText
import android.widget.TextView
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.adapter.PickWeeksGridViewAdapter
import com.sunshine.lnuplus.base.BaseActivity
import com.sunshine.lnuplus.callback.PickWeeksCallBack
import com.sunshine.lnuplus.model.InitData
import com.sunshine.lnuplus.model.LessonBean
import com.sunshine.lnuplus.model.room.CountDown
import com.sunshine.lnuplus.model.room.Lesson
import com.sunshine.lnuplus.model.room.TimetableRepository
import com.sunshine.lnuplus.utils.DateUtils
import com.sunshine.lnuplus.utils.StatusBarUtils
import com.sunshine.lnuplus.utils.UpdateWidgetUtils
import com.sunshine.lnuplus.view.DialogWithView
import com.sunshine.lnuplus.view.DialogWithoutView
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.activity_add_lesson.*
import kotlinx.android.synthetic.main.dialog_lesson_edit.*
import kotlinx.android.synthetic.main.dialog_lesson_edit.view.*
import kotlinx.android.synthetic.main.dialog_lesson_edit.view.pick_weeks
import kotlinx.android.synthetic.main.dialog_pick_color.view.*
import kotlinx.android.synthetic.main.dialog_pick_time.view.*
import kotlinx.android.synthetic.main.dialog_pick_weeks.view.*
import kotlinx.android.synthetic.main.item_lesson_edit.view.*

class AddLessonActivity : BaseActivity() {

    private val viewList = ArrayList<View>()
    private val timeList = HashMap<String, ArrayList<Int>>()
    private val weekList = HashMap<String, ArrayList<Int>>()
    private var backgroundColor = "0"
    private var dayOfWeek = 1
    private var time = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_lesson)
        initView()

        val bundle = intent.getBundleExtra("time")
        dayOfWeek = bundle.getInt("day_of_week")
        time = bundle.getInt("time")
    }

    private fun initView() {
        title = "添加课程"
        StatusBarUtils.setStatusBarWithColor(this, color)
        if(isNight) constraintLayout2.setBackgroundColor(Color.BLACK)

        getToolBar()?.setNavigationOnClickListener {
            initDialog()
        }

        addView()
        fab_add_lesson.setOnClickListener {
            addView()
        }

        //选择背景颜色
        pick_my_color.setOnClickListener {
            val view = LayoutInflater.from(this).inflate(R.layout.dialog_pick_color, null, false)
            var tempColor = "#ff0000"
            val pickColor = DialogWithView.newInstance(
                view,
                "请选择课程背景颜色",
                false,
                DialogInterface.OnClickListener { _, _ ->
                    backgroundColor = tempColor
                    pick_my_color.setTextColor(if(backgroundColor == "0") Color.parseColor("#000000") else Color.parseColor(backgroundColor))
                },
                null)
            pickColor.show(supportFragmentManager, "pickColor")
            view.color_pick_view.setOnColorChangeListener {
                tempColor = String.format("%08x",it)
                tempColor = "#" + tempColor.substring(2, tempColor.length)
            }

            view.button_color_default.setOnClickListener {
                backgroundColor = "0"
                pick_my_color.setTextColor(Color.parseColor("#000000"))
                pickColor.dismiss()
            }
        }
    }

    private fun addView() {
        val lessonView =
            LayoutInflater.from(this).inflate(R.layout.item_lesson_edit, add_lesson_layout, false)
        add_lesson_layout.addView(lessonView)
        if(isNight) {
            lessonView.add_lesson_cardview.setCardBackgroundColor(Color.BLACK)
            lessonView.findViewById<TextView>(R.id.edit_title).setTextColor(Color.WHITE)
            lessonView.findViewById<Button>(R.id.pick_weeks).setTextColor(Color.WHITE)
            lessonView.findViewById<Button>(R.id.button_pick_time).setTextColor(Color.WHITE)
        }
        viewList.add(lessonView)
        lessonView.findViewById<Button>(R.id.button_delete).setOnClickListener {
            val dialog = DialogWithoutView.newInstance(
                "警告",
                "你要删除这个时间段吗",
                false,
                DialogInterface.OnClickListener { _, _ ->
                    add_lesson_layout.removeView(lessonView)
                    viewList.remove(lessonView)
                },
                null
            )
            dialog.show(supportFragmentManager, "addlesson")
        }
        lessonView.findViewById<TextView>(R.id.edit_title).text = "时段${viewList.size}"
        lessonView.findViewById<Button>(R.id.pick_weeks).setOnClickListener {
            val view = LayoutInflater.from(this).inflate(R.layout.dialog_pick_weeks, null, false)
            var tempWeekList = ArrayList<Int>()
            val callBack = object : PickWeeksCallBack {
                override fun callBack(weekList: List<Int>) {
                    tempWeekList = weekList as ArrayList<Int>
                }
            }
            view.pick_weeks_view.adapter = PickWeeksGridViewAdapter(this, null, callBack)
            val pickWeek = DialogWithView.newInstance(
                view,
                "请选择上课周数",
                false,
                DialogInterface.OnClickListener { _, _ ->
                    lessonView.findViewById<Button>(R.id.pick_weeks).pick_weeks.text =
                        "$tempWeekList"
                    weekList["时段${viewList.size}"] = tempWeekList
                },
                null
            )
            pickWeek.show(supportFragmentManager, "pickWeek")
            view.all_week.setOnClickListener {
                view.pick_weeks_view.adapter = PickWeeksGridViewAdapter(this, null, callBack)
            }
            view.dan_week.setOnClickListener {
                val danWeekList = ArrayList<Int>()
                for (i in 1..InitData.lessonStyle.weekCount) {
                    if (i % 2 != 0) {
                        danWeekList.add(i)
                    }
                }
                view.pick_weeks_view.adapter = PickWeeksGridViewAdapter(
                    this,
                    danWeekList,
                    callBack
                )
            }
            view.shuang_week.setOnClickListener {
                val shuangWeekList = ArrayList<Int>()
                for (i in 1..InitData.lessonStyle.weekCount) {
                    if (i % 2 == 0) {
                        shuangWeekList.add(i)
                    }
                }
                view.pick_weeks_view.adapter = PickWeeksGridViewAdapter(
                    this,
                    shuangWeekList,
                    callBack
                )
            }
        }
        //选择时间按钮
        lessonView.findViewById<Button>(R.id.button_pick_time).setOnClickListener {
            val lessonCount = InitData.lessonStyle.count
            val view = LayoutInflater.from(this).inflate(R.layout.dialog_pick_time, null, false)
            val lessonCountString = arrayOfNulls<String>(lessonCount)
            for (i in 1..lessonCount) {
                lessonCountString[i - 1] = "第${i}节"
            }
            view.pick_week.apply {
                displayedValues = arrayOf("周一", "周二", "周三", "周四", "周五", "周六", "周日")
                minValue = 0
                maxValue = 6
                descendantFocusability = DatePicker.FOCUS_BLOCK_DESCENDANTS
                value = dayOfWeek - 1
            }
            view.pick_start.apply {
                displayedValues = lessonCountString
                minValue = 0
                maxValue = lessonCount - 1
                descendantFocusability = DatePicker.FOCUS_BLOCK_DESCENDANTS
                setOnValueChangedListener { _, _, newVal ->
                    if (newVal > view.pick_end.value) view.pick_end.value = newVal
                }
                value = time - 1
            }
            view.pick_end.apply {
                displayedValues = lessonCountString
                minValue = 0
                maxValue = lessonCount - 1
                descendantFocusability = DatePicker.FOCUS_BLOCK_DESCENDANTS
                setOnValueChangedListener { _, _, newVal ->
                    if (newVal < view.pick_start.value) view.pick_start.value = newVal
                }
                value = time - 1
            }
            val pickTime = DialogWithView.newInstance(
                view,
                "请选择上课时间",
                false,
                DialogInterface.OnClickListener { _, _ ->
                    val dayOfWeek = view.pick_week.value + 1
                    val start = view.pick_start.value + 1
                    val end = view.pick_end.value + 1

                    val arrayList = ArrayList<Int>()
                    arrayList.apply {
                        add(dayOfWeek)
                        add(start)
                        add(end)
                    }
                    timeList["时段${viewList.size}"] = arrayList

                    lessonView.findViewById<Button>(R.id.button_pick_time).text =
                        "周${DateUtils.getTodayOfWeekString(dayOfWeek)} 第${start}节-第${end}节"
                },
                null
            )
            pickTime.show(supportFragmentManager, "pickTime")
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.add_lesson_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if(item.itemId == R.id.tosave){
            when {
                edit_lesson_name_add.text.toString().isEmpty() -> {
                    til_lesson_name_add.error = "课程名称不能为空呀~"
                    til_lesson_name_add.isErrorEnabled = true
                }
                edit_lesson_name_add.text.toString().length > 30 -> {
                    til_lesson_name_add.error = "课程名称过长，我可能记不住~"
                    til_lesson_name_add.isErrorEnabled = true
                }
                else -> {
                    viewList.forEach {
                        til_lesson_name_add.isErrorEnabled = false
                        val repository = TimetableRepository(this)
                        if(weekList[it.findViewById<TextView>(R.id.edit_title).text.toString()] == null){
                            val defaultWeekList = ArrayList<Int>()
                            for(i in 1..InitData.lessonStyle.weekCount){
                                defaultWeekList.add(i)
                            }
                            weekList[it.findViewById<TextView>(R.id.edit_title).text.toString()] = defaultWeekList
                        }
                        if(timeList[it.findViewById<TextView>(R.id.edit_title).text.toString()] == null){
                            val defaultTimeList = ArrayList<Int>()
                            defaultTimeList.add(dayOfWeek)
                            defaultTimeList.add(time)
                            defaultTimeList.add(time)
                            timeList[it.findViewById<TextView>(R.id.edit_title).text.toString()] = defaultTimeList
                        }
                        val newLessonBean = LessonBean(
                            "${DateUtils.year}${DateUtils.month}${DateUtils.day}${DateUtils.hour}${DateUtils.minute}${DateUtils.second}",
                            edit_lesson_name_add.text.toString(),
                            timeList[it.findViewById<TextView>(R.id.edit_title).text.toString()]!![0],
                            timeList[it.findViewById<TextView>(R.id.edit_title).text.toString()]!![1],
                            timeList[it.findViewById<TextView>(R.id.edit_title).text.toString()]!![2],
                            it.findViewById<EditText>(R.id.edit_location).text.toString(),
                            it.findViewById<EditText>(R.id.edit_teacher).text.toString(),
                            backgroundColor,
                            weekList[it.findViewById<TextView>(R.id.edit_title).text.toString()]!!
                        )
                        InitData.lessonList?.add(newLessonBean)
                        repository.insertLesson(
                            Lesson(
                                "${DateUtils.year}${DateUtils.month}${DateUtils.day}${DateUtils.hour}${DateUtils.minute}${DateUtils.second}",
                                timeList[it.findViewById<TextView>(R.id.edit_title).text.toString()]!![0],
                                timeList[it.findViewById<TextView>(R.id.edit_title).text.toString()]!![1],
                                "",
                                timeList[it.findViewById<TextView>(R.id.edit_title).text.toString()]!![2],
                                "",
                                edit_lesson_name_add.text.toString(),
                                it.findViewById<EditText>(R.id.edit_teacher).text.toString(),
                                it.findViewById<EditText>(R.id.edit_location).text.toString(),
                                weekList[it.findViewById<TextView>(R.id.edit_title).text.toString()]!!.toString().replace("[","").replace("]",""),
                                backgroundColor
                            )
                        )
                        repository.insertCountDown(
                            CountDown(
                                edit_lesson_name_add.text.toString(),
                                "",
                                9999,
                                9999,
                                9999,
                                9999,
                                9999,
                                "",
                                backgroundColor
                            )
                        )
                        Toasty.success(this, "保存成功", Toasty.LENGTH_SHORT).show()
                        UpdateWidgetUtils.updateWidgets(this)
                        setResult(Activity.RESULT_OK)
                        finish()
                    }
                }
            }
        }
        return true
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK && event?.action == KeyEvent.ACTION_DOWN) {
            initDialog()
            true
        } else {
            super.onKeyDown(keyCode, event)
        }
    }

    private fun initDialog() {
        val dialog = DialogWithoutView.newInstance(
            "警告",
            "你真的要返回吗？从这里返回数据就不保存了噢，如果想保存数据请点击右上角保存按钮。",
            false,
            DialogInterface.OnClickListener { _, _ ->
                finish()
            },
            null)
        dialog.show(supportFragmentManager, "addLesson")
    }
}
